package com.thewaybetter.modules.server.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.thewaybetter.modules.client.model.SlimIdea;
import com.thewaybetter.modules.client.services.IdeaService;
import com.thewaybetter.modules.server.dao.factory.PMF;
import com.thewaybetter.modules.server.model.Idea;

@SuppressWarnings("serial")
public class IdeaServiceImpl extends RemoteServiceServlet implements
		IdeaService {

	public SlimIdea save(SlimIdea i) {
		PMF.saveObject(new Idea(i));
		return i;
	}
	
	public List<SlimIdea> getAll() {
		Query query = PMF.getManager().newQuery(Idea.class);
		query.setOrdering("updatedAt ascending");
		ArrayList<SlimIdea> result = new ArrayList<SlimIdea>();
		List<Idea> resultset = (List<Idea>)query.execute();
		for (Idea a: resultset){
			result.add(a.convert());
		}
		return result;
	}
	
	public List<SlimIdea> getNew(Date now) {
		PersistenceManager manager = PMF.getManager();
		Query q = manager.newQuery(Idea.class);
		ArrayList<SlimIdea> result = new ArrayList<SlimIdea>();
		List<Idea> resultset = (List<Idea>)q.execute();
		for (Idea a: resultset){
			if (a.getUpdatedAt().after(now)){
				result.add(a.convert());
			}
		}
		return result;
	}
	
	public String clearAll(){
		PersistenceManager manager = PMF.getManager(); 
		Query query = manager.newQuery(Idea.class);
		ArrayList<SlimIdea> result = new ArrayList<SlimIdea>();
		List<Idea> resultset = (List<Idea>)query.execute();
		for (Idea a: resultset){
			manager.deletePersistent(a);
		}
		return "ok";
	}
	
}
